import React, { useState, useEffect } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import {
  NavBar,
  Image,
  Card,
  Button,
  Space,
  Tag,
  Toast,
  Dialog,
  Steps
} from 'antd-mobile';
import { RightOutline } from 'antd-mobile-icons';
import './OrderDetail.css';
import { useRequest } from 'ahooks';
import { cancelOrder, updateOrder } from '../../api/store';
import { getOrders } from '../../api/dashboard';
const { Step } = Steps;

// 订单详情页面
const OrderDetail = () => {
  const navigate = useNavigate();
  const { orderId } = useParams();
  const [order, setOrder] = useState(null);
  const [loading, setLoading] = useState(true);
  const { runAsync: cancelOrderAsync } = useRequest(cancelOrder, { manual: true });
  const { runAsync: getOrdersAsync } = useRequest(getOrders, { manual: true });
  const { runAsync: updateOrderAsync } = useRequest(updateOrder, { manual: true });

  const fetchOrders = async () => {
    setLoading(true);

    try {
      // 从本地存储获取订单数据
      const orders = await getOrdersAsync({ params: { id: 1 } });
      const foundOrder = orders.find(o => o.id === orderId);

      if (!foundOrder) {
        Toast.show({
          icon: 'fail',
          content: '订单不存在',
        });
        navigate('/order/list');
        return;
      }

      setOrder(foundOrder);
    } catch (error) {
      console.error('获取订单失败:', error);
      Toast.show({
        icon: 'fail',
        content: '获取订单数据失败',
      });
      navigate('/order/list');
    }
    setLoading(false);
  }

  // 获取订单数据
  useEffect(() => {
    fetchOrders();
  }, [orderId, navigate]);

  // 返回上一页
  const back = () => {
    // 通过history返回上一页
    navigate(-1);

    // 延迟设置标记，表示我们即将返回到列表页
    // 这个标记将在OrderList组件中被检测，并触发页面刷新
    setTimeout(() => {
      sessionStorage.setItem('fromOrderDetail', 'true');
    }, 100);
  };

  // 获取订单状态文本
  const getOrderStatusText = (status) => {
    switch (status) {
      case 'pending':
        return '待付款';
      case 'paid':
        return '待发货';
      case 'shipped':
        return '待收货';
      case 'completed':
        return '已完成';
      case 'cancelled':
        return '已取消';
      default:
        return '未知状态';
    }
  };

  // 获取订单状态步骤
  const getOrderStep = (status) => {
    switch (status) {
      case 'pending':
        return 0;
      case 'paid':
        return 1;
      case 'shipped':
        return 2;
      case 'completed':
        return 3;
      default:
        return 0;
    }
  };

  // 处理取消订单
  const handleCancelOrder = () => {
    Dialog.confirm({
      content: '确认取消该订单吗？',
      onConfirm: async () => {
        const res = await cancelOrderAsync({ id: orderId });
        // 更新当前订单状态
        setOrder(res.orders);
        Toast.show({
          icon: 'success',
          content: '订单已取消',
        });
      },
    });
  };

  // 处理付款
  const handlePayOrder = () => {
    navigate(`/order/payment/${orderId}`);
  };

  // 处理确认收货
  const handleConfirmReceipt = () => {
    Dialog.confirm({
      content: '确认已收到商品吗？确认后订单将变为已完成状态。',
      onConfirm: async () => {
        try {
          // 直接更新当前订单状态
          await updateOrderAsync({
            id: orderId,
            status: 'completed',
            completionTime: new Date().toISOString(),
            receiptConfirmTime: new Date().toISOString()
          });

          // 更新当前订单状态
          setOrder(prev => ({
            ...prev,
            status: 'completed',
            completionTime: new Date().toISOString(),
            receiptConfirmTime: new Date().toISOString()
          }));

          Toast.show({
            icon: 'success',
            content: '已确认收货，感谢您的购买！',
            duration: 3000
          });

          // 延迟后自动返回到订单列表页
          setTimeout(() => {
            // 设置标记，确保返回列表页后页面会刷新
            sessionStorage.setItem('fromOrderDetail', 'true');
            navigate('/order/list');
          }, 2000);
        } catch (error) {
          console.error('确认收货失败:', error);
          Toast.show({
            icon: 'fail',
            content: '确认收货失败，请重试',
          });
        }
      },
    });
  };

  // 格式化日期
  const formatDate = (dateString) => {
    if (!dateString) return '';
    const date = new Date(dateString);
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
  };

  // 渲染订单状态
  const renderOrderStatus = () => {
    if (!order) return null;

    return (
      <div className={`order-status-section ${order.status === 'completed' ? 'completed' : ''}`}>
        <div className="order-status-header">
          <div className={`order-status-text ${order.status === 'completed' ? 'completed' : ''}`}>
            {getOrderStatusText(order.status)}
          </div>
          {order.status === 'cancelled' && (
            <div className="order-cancel-reason">
              订单已取消
            </div>
          )}
        </div>

        {order.status !== 'cancelled' && (
          <div className="steps-container" data-current={getOrderStep(order.status)}>
            <Steps
              current={getOrderStep(order.status)}
              direction='horizontal'
            >
              <Step title='下单' description={formatDate(order.createTime)} />
              <Step title='付款' description={formatDate(order.payTime)} />
              <Step title='发货' description={order.shipTime ? formatDate(order.shipTime) : '待发货'} />
              <Step title='收货' description={order.completionTime ? formatDate(order.completionTime) : '待收货'} />
            </Steps>
          </div>
        )}
      </div>
    );
  };

  // 渲染收货地址
  const renderAddress = () => {
    if (!order || !order.address) return null;

    const { name, phone, province, city, district, address } = order.address;

    return (
      <Card className="order-card">
        <div className="card-header">
          <div className="card-title">收货地址</div>
        </div>
        <div className="address-info">
          <div className="address-contact">
            <span className="contact-name">{name}</span>
            <span className="contact-phone">{phone}</span>
          </div>
          <div className="address-detail">
            {`${province}${city}${district}${address}`}
          </div>
        </div>
      </Card>
    );
  };

  // 渲染订单商品
  const renderOrderItems = () => {
    if (!order || !order.orderItems) return null;

    return (
      <Card className="order-card">
        <div className="card-header">
          <div className="card-title">商品信息</div>
        </div>
        <div className="order-items">
          {order.orderItems.map(item => (
            <div
              key={item.id}
              className="order-item"
              onClick={() => navigate(`/product/${item.id}`)}
            >
              <div className="item-image">
                <Image
                  src={item.image}
                  fit='cover'
                  width={80}
                  height={80}
                />
              </div>
              <div className="item-info">
                <div className="item-name">{item.name}</div>
                <div className="item-price-qty">
                  <span className="item-price">¥{item.price.toFixed(2)}</span>
                  <span className="item-quantity">x{item.quantity}</span>
                </div>
              </div>
            </div>
          ))}
        </div>
        <div className="order-total">
          <div className="total-item">
            <span>商品总价</span>
            <span>¥{order.totalPrice.toFixed(2)}</span>
          </div>
          <div className="total-item">
            <span>运费</span>
            <span>¥0.00</span>
          </div>
          <div className="total-item order-actual-total">
            <span>实付款</span>
            <span className="actual-price">¥{order.totalPrice.toFixed(2)}</span>
          </div>
        </div>
      </Card>
    );
  };

  // 渲染订单信息
  const renderOrderInfo = () => {
    if (!order) return null;

    return (
      <Card className="order-card">
        <div className="card-header">
          <div className="card-title">订单信息</div>
        </div>
        <div className="order-info-list">
          <div className="info-item">
            <span className="info-label">订单编号</span>
            <span className="info-value">{order.id}</span>
          </div>
          <div className="info-item">
            <span className="info-label">创建时间</span>
            <span className="info-value">{formatDate(order.createTime)}</span>
          </div>
          <div className="info-item">
            <span className="info-label">支付方式</span>
            <span className="info-value">
              {order.paymentMethod === 'alipay' ? '支付宝' :
                order.paymentMethod === 'wechat' ? '微信支付' : '货到付款'}
            </span>
          </div>
          {order.payTime && (
            <div className="info-item">
              <span className="info-label">支付时间</span>
              <span className="info-value">{formatDate(order.payTime)}</span>
            </div>
          )}
          {order.shipTime && (
            <div className="info-item">
              <span className="info-label">发货时间</span>
              <span className="info-value">{formatDate(order.shipTime)}</span>
            </div>
          )}
          {order.completionTime && (
            <div className="info-item">
              <span className="info-label">完成时间</span>
              <span className="info-value">{formatDate(order.completionTime)}</span>
            </div>
          )}
          {order.receiptConfirmTime && (
            <div className="info-item">
              <span className="info-label">确认收货时间</span>
              <span className="info-value">{formatDate(order.receiptConfirmTime)}</span>
            </div>
          )}
          {order.cancelTime && (
            <div className="info-item">
              <span className="info-label">取消时间</span>
              <span className="info-value">{formatDate(order.cancelTime)}</span>
            </div>
          )}
          {order.trackingNumber && (
            <div className="info-item">
              <span className="info-label">物流单号</span>
              <span className="info-value">{order.trackingNumber}</span>
            </div>
          )}
          {order.remark && (
            <div className="info-item">
              <span className="info-label">订单备注</span>
              <span className="info-value">{order.remark}</span>
            </div>
          )}
        </div>
      </Card>
    );
  };

  // 渲染底部按钮
  const renderFooterButtons = () => {
    if (!order) return null;

    // 辅助函数：设置标记并导航到指定路径
    const navigateWithFlag = (path) => {
      setTimeout(() => {
        sessionStorage.setItem('fromOrderDetail', 'true');
      }, 100);
      navigate(path);
    };

    switch (order.status) {
      case 'pending':
        return (
          <div className="order-footer">
            <Button onClick={handleCancelOrder}>取消订单</Button>
            <Button color='primary' onClick={handlePayOrder}>去支付</Button>
          </div>
        );
      case 'paid':
        return (
          <div className="order-footer">
            <Button onClick={() => navigateWithFlag('/order/list')}>查看全部订单</Button>
            <Button>联系客服</Button>
          </div>
        );
      case 'shipped':
        return (
          <div className="order-footer">
            <Button size="middle">查看物流</Button>
            <Button color='primary' size="middle" onClick={handleConfirmReceipt}>确认收货</Button>
          </div>
        );
      case 'completed':
        return (
          <div className="order-footer">
            <Button onClick={() => Toast.show('评价功能开发中')}>评价商品</Button>
            <Button onClick={() => Toast.show('申请售后功能开发中')}>申请售后</Button>
            <Button onClick={() => navigate('/home')}>再次购买</Button>
          </div>
        );
      case 'cancelled':
        return (
          <div className="order-footer">
            <Button onClick={() => navigate('/home')}>继续购物</Button>
            <Button>删除订单</Button>
          </div>
        );
      default:
        return null;
    }
  };

  if (loading) {
    return (
      <div className="loading-container">
        <div className="loading-spinner">加载中...</div>
      </div>
    );
  }

  return (
    <div className="order-detail-container">
      {/* 导航栏 */}
      <NavBar onBack={back}>订单详情</NavBar>

      {/* 订单状态 */}
      {renderOrderStatus()}

      {/* 收货地址 */}
      {renderAddress()}

      {/* 商品信息 */}
      {renderOrderItems()}

      {/* 订单信息 */}
      {renderOrderInfo()}

      {/* 底部空间，防止内容被按钮遮挡 */}
      <div style={{ height: '70px' }}></div>

      {/* 底部按钮 */}
      {renderFooterButtons()}
    </div>
  );
};

export default OrderDetail; 